package com.neusoft.config;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局异常处理器
 *
 * @author Lucifer
 * @since 2021/5/16 8:18
 */
@RestControllerAdvice(basePackages = "com.neusoft.controller")
public class MyExceptionHandler implements ResponseBodyAdvice<Object> {

    @ExceptionHandler(value = Exception.class)
    public Result handle(Exception e) {
        e.printStackTrace();
        return Result.error(e.getMessage());
    }


    /**
     * 用于判定是否进入beforeBodyWrite方法
     *
     * @param methodParameter 方法参数
     * @param aClass          Http消息转换
     * @return true.进入，false.不进入
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        String typeName = methodParameter.getMethod().getReturnType().getSimpleName();
        if (typeName.equals("void")) {
            return Result.SUCCESS;
        }
        return Result.SUCCESS(o);
    }
}
